package l.l.w.leetcode.NextPermutation;

/**
 * Created by llw on 2017/11/4.
 */
public class NextPermutation {
    public void nextPermutation(int[] nums) {
        if(nums == null || nums.length==0 || nums.length ==1) return;
        int index = -1,end=0;
        for(int i = 0; i < nums.length-1; ++i){
            int dif = Integer.MAX_VALUE;
            for(int j = i+1; j < nums.length; ++j){
                if(nums[i] < nums[j] && nums[j]-nums[i]<dif){
                    dif = nums[j]-nums[i];
                    index = i;
                    end = j;
                }
            }
        }
        if(index == -1) reverse(nums,0,nums.length-1);
        else{
            exchange(nums,index,end);
            inPlaceSort(nums,index+1,nums.length-1);
        }
    }

    private void inPlaceSort(int[] nums, int i, int j) {
        for(;i<j;++i){
            int minIndex = i;
            for(int k = i+1; k<=j;++k){
                if(nums[k] < nums[minIndex]){
                    minIndex = k;
                }
            }
            exchange(nums,i,minIndex);
        }
    }

    private void reverse(int[] nums, int i, int j) {
        for(; i < j; ++i,--j){
            exchange(nums,i,j);
        }
    }

    private void exchange(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}
